package com.hh.controller;

import com.hh.entity.domain.User;
import com.hh.entity.enums.BehaviorType;
import com.hh.service.ArticleViewsService;
import com.hh.service.UserBehaviorService;
import com.hh.service.UserService;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * com.hh.controller
 *
 * @author hanhui
 * @version 0.0.1
 * @date 2025/5/31
 * 文章视图控制器
 * 处理文章浏览相关的请求，包括增加文章浏览量等功能
 */
@RestController
public class ArticleViewController {

    /**
     * 注入文章浏览服务
     */
    @Resource
    private ArticleViewsService articleViewService;

    /**
     * 注入用户行为服务
     */
    @Resource
    private UserBehaviorService userBehaviorService;

    /**
     * 注入用户服务
     */
    @Resource
    private UserService userService;

    /**
     * 增加文章浏览量
     *
     * @param articleId 文章ID
     * @param request HTTP请求对象
     * @return 包含操作结果的Map，键为"count"，值为"incremented"
     */
    @PostMapping("/view/{articleId}")
    public Map<String, String> incrementView(@PathVariable Long articleId, HttpServletRequest request) {
        // 生成唯一用户标识
        String userKey = request.getRemoteAddr() + ":" + request.getHeader("User-Agent");
        User loginUser = userService.getLoginUser(request);
        Long userId = loginUser.getId();
        articleViewService.incrementViewCount(articleId, userKey);
        Map<String, String> result = new HashMap<>();
        result.put("count", "incremented");
        userBehaviorService.addBehavior(userId, articleId, BehaviorType.VIEW.getValue());
        return result;
    }
}
